package com.chase.framerwork.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.chase.framerwork.exception.SysException;

/**
 * 
 * Excel工厂
 * 
 * @Author Chase
 * @Date 2013-10-13
 */
public class ExcelFactroy
{

	private static ExcelFactroy excelFactroy = null;

	private ExcelFactroy()
	{
	}

	/**
	 * 得到工厂实例
	 * 
	 * @return
	 */
	public static synchronized ExcelFactroy getInstance()
	{
		if (excelFactroy == null)
		{
			excelFactroy = new ExcelFactroy();
		}
		return excelFactroy;
	}

	/**
	 * 创建Excel
	 * 
	 * @param sheetName
	 *            Sheet页名称
	 * @param fileName
	 *            导出的文件名
	 * @return
	 */
	public Excel createExcel(String sheetName, String fileName)
	{

		Excel excel = new Excel();

		HSSFWorkbook workbook = new HSSFWorkbook();

		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, sheetName);

		excel.setWorkbook(workbook);
		excel.setSheet(sheet);
		excel.setSheetName(sheet.getSheetName());
		excel.setFileName(fileName);

		return excel;
	}

	/**
	 * 读取Excel
	 * @param upload 
	 * 
	 * @param filePath 文件路径
	 * @param sheetNum 读取的Sheet页码
	 * @return
	 */
	public Excel readExcel(File file, String fileName)
	{

		Excel excel = new Excel();
		Workbook workbook = null;

		boolean isXls = isXlS(fileName);
		try
		{
			if (isXls)
			{
				excel.setExcelFileType(ExcelFileType.xls);
				POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file.getAbsolutePath()));
				workbook = new HSSFWorkbook(fs);
			}
			else
			{
				excel.setExcelFileType(ExcelFileType.xlsx);
				workbook = new XSSFWorkbook(new FileInputStream(file.getAbsolutePath()));
			}
		}
		catch (FileNotFoundException e)
		{
			throw new SysException("Excel读取失败:系统找不到指定文件");
		}
		catch (IOException e)
		{
			throw new SysException("Excel读取失败:文件可能正在被其他应用程序使用");
		}

		excel.setWorkbook(workbook);
		Sheet sheet = workbook.getSheetAt(0);
		excel.setSheet(sheet);
		excel.setSheetName(sheet.getSheetName());

		return excel;
	}

	/**
	 * 判断Excel类型
	 * 
	 * @param filePath
	 * @return
	 */
	private boolean isXlS(String filePath)
	{
		if (StringUtils.isEmpty(filePath))
		{
			throw new SysException("Excel读取失败:找不到文件路径");
		}

		if (filePath.contains(".xlsx"))
		{
			return false;
		}
		return true;
	}
}
